package org.edu.modules.stu.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.edu.common.api.vo.Result;
import org.edu.common.base.BasePageDto;
import org.edu.common.base.BaseServiceImpl;
import org.edu.common.constant.RoleConstant;
import org.edu.common.dto.BaseCountDto;
import org.edu.common.system.api.ISysBaseAPI;
import org.edu.common.utils.ConvertUtils;
import org.edu.common.utils.DateUtil;
import org.edu.modules.stu.base.dto.*;
import org.edu.modules.stu.base.mapper.VeBaseStudentMapper;
import org.edu.modules.stu.base.entity.VeBaseStudent;
import org.edu.modules.stu.base.service.VeBaseStudentInfoService;
import org.edu.modules.stu.base.service.VeBaseStudentService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import org.edu.modules.stu.base.service.VeStuFamilyService;
import org.edu.modules.stu.biye.dto.VeStuGraduationAuditInfoDto;
import org.edu.modules.stu.common.entity.VeBaseAppUser;
import org.edu.modules.stu.common.service.VeBaseAppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 实现类
 */
@Service
public class VeBaseStudentServiceImpl extends BaseServiceImpl<VeBaseStudent, VeBaseStudentMapper> implements VeBaseStudentService {

    @Autowired
    private VeBaseStudentInfoService infoService;
    @Autowired
    private VeStuFamilyService veStuFamilyService;
    @Autowired
    private ISysBaseAPI iSysBaseAPI;
    @Autowired
    private VeBaseStudentMapper veBaseStudentMapper;
    @Autowired
    private VeBaseAppUserService veBaseAppUserService;

    @Override
    public List<BaseCountDto> countDto(String year) {
        if (StrUtil.isNotEmpty(year)) {
            year = year + "%";
        }
        return mapper.countDto(year);
    }

    public IPage<VeBaseStudentDto> pageDto(BasePageDto page, @Param(Constants.WRAPPER) Wrapper queryWrapper) {
        IPage<VeBaseStudentDto> pageDto = mapper.pageDto(page, queryWrapper);
        return pageDto;
    }

    @Override
    public IPage<VeStuGraduationAuditInfoDto> pageGraduationDto(BasePageDto page, Wrapper queryWrapper) {
        return mapper.pageGraduationDto(page,queryWrapper);
    }

    @Override
    public IPage<VeBaseStudentDto> pageDtoByBanjinIds(BasePageDto page, Wrapper queryWrapper, String[] ids) {
        IPage<VeBaseStudentDto> pageDto = mapper.pageDtoByBanjinIds(page, queryWrapper, ids);
        return pageDto;
    }

    @Override
    public Map<String, Integer> batchGetIdBySfzh(Set<String> allSfzh) {
        if (allSfzh.isEmpty()) {
            return Collections.emptyMap();  // 空集合快速返回
        }

        // 分页查询避免IN子句过长（例如Oracle限制1000条）
        List<VeBaseStudent> students = splitQueryByPage(allSfzh, 500);

        return students.stream()
                .collect(Collectors.toMap(
                        VeBaseStudent::getSfzh,
                        student -> student.getId(),
                        (oldId, newId) -> oldId // 处理重复sfzh，保留首次出现的ID
                ));
    }

    @Override
    public Map<String, Integer> batchGetXhByNumbers(Set<String> allXh) {
        if (allXh.isEmpty()) {
            return Collections.emptyMap();  // 空集合快速返回
        }

        // 分页查询避免IN子句过长（例如Oracle限制1000条）
        List<VeBaseStudent> students = splitQueryByPageForXh(allXh, 500);

        return students.stream()
                .collect(Collectors.toMap(
                        VeBaseStudent::getXh,
                        student -> student.getId(),
                        (oldId, newId) -> oldId // 处理重复xh，保留首次出现的ID
                ));
    }

    /**
     * 分片查询（防止SQL过长）
     */
    private List<VeBaseStudent> splitQueryByPage(Set<String> sfzhSet, int pageSize) {
        List<String> sfzhList = new ArrayList<>(sfzhSet);
        List<VeBaseStudent> result = new ArrayList<>();

        for (int i = 0; i < sfzhList.size(); i += pageSize) {
            int end = Math.min(i + pageSize, sfzhList.size());
            List<String> subList = sfzhList.subList(i, end);

            // 执行SQL查询（MyBatis示例）
            LambdaQueryWrapper<VeBaseStudent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(VeBaseStudent::getSfzh, subList);
            result.addAll(veBaseStudentMapper.selectList(queryWrapper));
        }
        return result;
    }

    /**
     * 分片查询（防止SQL过长）
     */
    private List<VeBaseStudent> splitQueryByPageForXh(Set<String> xhSet, int pageSize) {
        List<String> sfzhList = new ArrayList<>(xhSet);
        List<VeBaseStudent> result = new ArrayList<>();

        for (int i = 0; i < sfzhList.size(); i += pageSize) {
            int end = Math.min(i + pageSize, sfzhList.size());
            List<String> subList = sfzhList.subList(i, end);

            // 执行SQL查询（MyBatis示例）
            LambdaQueryWrapper<VeBaseStudent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(VeBaseStudent::getXh, subList);
            result.addAll(veBaseStudentMapper.selectList(queryWrapper));
        }
        return result;
    }

    /**
     * 查询实体类
     */
    public VeBaseStudentDto findDtoById(String id) {
        VeBaseStudent entity = super.findById(id);
        VeBaseStudentDto dto = ConvertUtils.convertToDto(entity, VeBaseStudentDto.class);
        return dto;
    }

    /**
     * 查询实体类
     */
    public VeBaseStudentDto findDtoByXh(String xh) {
        LambdaQueryWrapper<VeBaseStudent> wrapper = new LambdaQueryWrapper<VeBaseStudent>();
        wrapper.eq(VeBaseStudent::getXh, xh);
        VeBaseStudent entity = mapper.selectOne(wrapper);
        VeBaseStudentDto dto = ConvertUtils.convertToDto(entity, VeBaseStudentDto.class);
        return dto;
    }

    /**
     * 新增或者修改
     */
    @Transactional
    public void insertOrUpdate(VeStudentVo dto, Boolean isAdd) {
        //地区id转名称
        areaIdToName(dto);
        //用户同步新增
        VeBaseStudent veBaseStudent = dto.getStu();
        addUserByVeBaseStudent(veBaseStudent);

        if (isAdd) {
            Long time = DateUtil.now().getTime();
            veBaseStudent.setCreateTime((int) (time / 1000));
            veBaseStudent.setUpdateTime((int) (time / 1000));
            veBaseStudent.setUserId(veBaseStudent.getXh());
            super.insert(veBaseStudent);
            VeBaseStudentInfoDto stuInfo = dto.getStuInfo();
            //  stuInfo.setId(veBaseStudent.getId());
            stuInfo.setStuId(veBaseStudent.getId());
            stuInfo.setUpdateTime(veBaseStudent.getUpdateTime());
            infoService.insertOrUpdate(stuInfo, true);
        } else {
            if (dto.getFamily() != null) {
                veStuFamilyService.deleteByStuId(veBaseStudent.getId());
            }
            try {
                super.update(veBaseStudent);
            } catch (Exception e) {
            }
            dto.getStuInfo().setStuId(veBaseStudent.getId());

            infoService.insertOrUpdate(dto.getStuInfo(), false);
        }

        if (dto.getFamily() != null && dto.getFamily().size() > 0) {
            //清空旧家庭信息
            veStuFamilyService.deleteByStuId(veBaseStudent.getId());
            //写入新家庭信息
            for (VeStuFamilyDto familyDto : dto.getFamily()) {
                familyDto.setCode(veBaseStudent.getXh());
                familyDto.setStuId(veBaseStudent.getId());
            }
            veStuFamilyService.insert(dto.getFamily());
        }
    }

    public void addUserByVeBaseStudent(VeBaseStudent veBaseStudent) {
        VeBaseAppUser veBaseAppUser = new VeBaseAppUser();
        veBaseAppUser.setId(UUID.randomUUID().toString().replace("-", ""));
        veBaseAppUser.setUserId(veBaseStudent.getXh());
        veBaseAppUser.setUserName(veBaseStudent.getXh());
        veBaseAppUser.setRealName(veBaseStudent.getXm());
        veBaseAppUser.setUserType("2");
        veBaseAppUser.setStatus("0");
        veBaseAppUser.setIsDel("0");
        veBaseAppUser.setUserPassword(veBaseStudent.getSfzh().substring(12, 18));
        veBaseAppUser.setStrength(this.veBaseAppUserService.pwdVerify(veBaseAppUser.getUserPassword()));
        VeBaseAppUser vemodel = new VeBaseAppUser();
        vemodel = this.veBaseAppUserService.getPwdAndSalt(veBaseAppUser);
        //判断是否有逻辑删除的用户数据
        LambdaQueryWrapper<VeBaseAppUser> veBaseAppUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        veBaseAppUserLambdaQueryWrapper.eq(VeBaseAppUser::getUserId, veBaseStudent.getXh());
//        veBaseAppUserLambdaQueryWrapper.eq(VeBaseAppUser::getIsDel, 1);
        VeBaseAppUser userDeleted = this.veBaseAppUserService.getOne(veBaseAppUserLambdaQueryWrapper);
        if (userDeleted != null) {
//            if ("1".equals(userDeleted.getIsDel())){
            vemodel.setId(userDeleted.getId());
            vemodel.setIsDel("0");

            this.veBaseAppUserService.updateById(vemodel);
//            }else {
//                throw new RuntimeException("学号："+veBaseStudent.getXh()+"已存在");
//            }
        } else {
            this.veBaseAppUserService.save(vemodel);
            this.veBaseAppUserService.addSysUser(vemodel);
        }
        //绑定学生角色
        //1、获取学生角色id
        Integer roleId = veBaseAppUserService.getIdByRoleCode(RoleConstant.SYS_ROLE_STUDENT);
        if (roleId != null) {
            //2、绑定用户角色关系
            addUserRole(veBaseAppUser.getUserId(), roleId);
        } else {
            throw new ServiceException("学生角色信息缺失");
        }

//        this.veBaseAppUserService.addSysRoleUser(vemodel.getUserId(), Integer.valueOf(1));
    }

    public void addUserRole(String userId, Integer roleId) {
//        this.veBaseAppUserService.deleteRole(userId);
        Map map = this.veBaseAppUserService.getSysRoleUser(userId, roleId);
        if ((map != null) && (map.size() > 0)) {
            throw new RuntimeException("该用户角色已存在! ");
        }
        this.veBaseAppUserService.addSysRoleUser(userId, roleId);

    }

    public void areaIdToName(VeStudentVo dto) {
        //生源地省id转换名称
        if ((!"".equals(dto.getStu().getShengId())) && (dto.getStu().getShengId() != null)) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStu().getShengId());
            if (areaName != null) {
                dto.getStu().setSheng(areaName);
            }
        }
        //生源地市id转换名称
        if ((!"".equals(dto.getStu().getShiId())) && (dto.getStu().getShiId() != null)) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStu().getShiId());
            if (areaName != null) {
                dto.getStu().setShi(areaName);
            }
        }
        //生源地区id转换名称
        if ((!"".equals(dto.getStu().getQuId())) && (dto.getStu().getQuId() != null)) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStu().getQuId());
            if (areaName != null) {
                dto.getStu().setQu(areaName);
            }
        }
        //户口所在地省id转换名称
        if ((!"".equals(dto.getStu().getProvinceId())) && (dto.getStu().getProvinceId() != null)) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStu().getProvinceId());
            if (areaName != null) {
                dto.getStu().setProvince(areaName);
            }
        }
        //户口所在地市id转换名称
        if ((!"".equals(dto.getStu().getCityId())) && (dto.getStu().getCityId() != null)) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStu().getCityId());
            if (areaName != null) {
                dto.getStu().setCity(areaName);
            }
        }
        //户口所在地区id转换名称
        if ((!"".equals(dto.getStu().getCountyId())) && (dto.getStu().getCountyId() != null)) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStu().getCountyId());
            if (areaName != null) {
                dto.getStu().setCounty(areaName);
            }
        }
        //籍贯所在地省
        if (dto.getStuInfo().getJgszProvinceId() != null) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStuInfo().getJgszProvinceId());
            if (areaName != null) {
                dto.getStuInfo().setJgszProvince(areaName);
            }
        }
        //籍贯所在地市
        if (dto.getStuInfo().getJgszCityId() != null) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStuInfo().getJgszCityId());
            if (areaName != null) {
                dto.getStuInfo().setJgszCity(areaName);
            }
        }
        //籍贯所在地区
        if (dto.getStuInfo().getJgszCountyId() != null) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStuInfo().getJgszCountyId());
            if (areaName != null) {
                dto.getStuInfo().setJgszCounty(areaName);
            }
        }
        //出生地所在地省
        if (dto.getStuInfo().getCsdszProvinceId() != null) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStuInfo().getCsdszProvinceId());
            if (areaName != null) {
                dto.getStuInfo().setCsdszProvince(areaName);
            }
        }
        //出生地所在地市
        if (dto.getStuInfo().getCsdszCityId() != null) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStuInfo().getCsdszCityId());
            if (areaName != null) {
                dto.getStuInfo().setCsdszCity(areaName);
            }
        }
        //出生地所在地区
        if (dto.getStuInfo().getCsdszCountyId() != null) {
            String areaName = veStuFamilyService.getDictAreaNameById(dto.getStuInfo().getCsdszCountyId());
            if (areaName != null) {
                dto.getStuInfo().setCsdszCounty(areaName);
            }
        }
    }

    @Override
    public List<VeBaseStudent> listByBanjinIds(String[] ids) {
        return veBaseStudentMapper.listByBanjinIds(ids);
    }

    @Override
    public List<BaseCountDto> countStudentAtSchool(String gradeId, String falId, String specId, String bjId) {
        return veBaseStudentMapper.countStudentAtSchool(gradeId, falId, specId, bjId);
    }

    @Override
    public List<BaseCountDto> graduateStatistics(Integer falId, Integer specId) {
        return veBaseStudentMapper.graduateStatistics(falId, specId);
    }

    @Override
    public void importExcel(List<Map<String, Object>> mapList) {
//        for (Map map: mapList) {
//            VeBaseStudentInfoDto dto = new VeBaseStudentInfoDto();
//                   //         dto.setStuId ((String)map.get(0000));
//                   //         dto.setCym ((String)map.get(0000));
//                   //         dto.setCsDate ((String)map.get(0000));
//                   //         dto.setJg ((String)map.get(0000));
//                   //         dto.setJkzkm ((String)map.get(0000));
//                   //         dto.setZzmmm ((String)map.get(0000));
//                   //         dto.setHklbm ((String)map.get(0000));
//                   //         dto.setSfsldrk ((String)map.get(0000));
//                   //         dto.setAddress ((String)map.get(0000));
//                   //         dto.setHomePhone ((String)map.get(0000));
//                   //         dto.setTc ((String)map.get(0000));
//                   //         dto.setPhone ((String)map.get(0000));
//                   //         dto.setEmail ((String)map.get(0000));
//                   //         dto.setPhoto ((String)map.get(0000));
//                   //         dto.setQq ((String)map.get(0000));
//                   //         dto.setSfdb ((String)map.get(0000));
//                   //         dto.setByxx ((String)map.get(0000));
//                   //         dto.setBmfsm ((String)map.get(0000));
//                   //         dto.setRxcj ((String)map.get(0000));
//                   //         dto.setJtdzStatus ((String)map.get(0000));
//                   //         dto.setXslxdhStatus ((String)map.get(0000));
//
//            super.insert(dto);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();

        for (Map map : mapList) {
            // 将 Map 转换为 JwKecheng 对象
            VeBaseStudent veBaseStudent = objectMapper.convertValue(map, VeBaseStudent.class);
            this.save(veBaseStudent);

        }
//        }

    }
}
